import {
  ModalForm,
  ProForm,
  ProFormText,
  StepsForm,
  // @ts-ignore
} from '@ant-design/pro-components';
// @ts-ignore
import {Button, Image, message} from 'antd';
// @ts-ignore
import React, {useEffect, useState} from 'react';
import {borrowBook, getCurrentUserById} from "@/services/ant-design-pro/api";

interface IProps {
  book: API.BookDetail;
}

const BorrowBox: React.FC<IProps> = ({book}) => {
  const [currentUser,setCurrentUser] = useState<API.CurrentUser>({})
  const getCurrentUser = async (userId: string) => {
    try {
      const res = await getCurrentUserById(userId);
      if (res.data) {
        setCurrentUser(res);
      }
    } catch (error) {
      console.log(error);
    }
  }
  useEffect(() => {
    if(localStorage.getItem("userId")){
      // @ts-ignore
      getCurrentUser(localStorage.getItem("userId")).then()
    }
  },[])

  const newTime = () => {
    let date = new Date()
    return date.toDateString() + " " + date.toTimeString()
  }

  const Components = {
    ProForm,
    ModalForm,
    StepsForm,
  };
  const [type] = useState<keyof typeof Components>('ModalForm');
  const FormComponents = Components[type as 'ModalForm'];

  const handleSubmit = async (values: API.BorrowParams) => {
    // 添加数据
    values.return_time = "";
    // 校验
    try {
      // 注册
      if(book.data){
        const res = await borrowBook({
          ...values,
        }, book.data.id);
        if (!res.data) {
          message.error(res.msg);
          return;
        } else {
          message.success('借阅成功');
        }
      }


    } catch (error) {
      const Message = '借阅失败，请重试！';
      console.log(error);
      message.error(Message);
    }
  };

  return (
    <>

      <FormComponents
        // @ts-ignore
        labelWidth="auto"
        title="书籍借阅"
        trigger={<Button type="primary">借阅</Button>}
        onFinish={async (values: any) => {
          await handleSubmit(values);
          console.log(values);
        }}
        style={{
          overflow:"hidden",
        }}
      >
        <div
          style={{
            float: "right",
          }}
        >
          {book.data && (
            <ProFormText
              width="lg"
              name="book_id"
              label="书籍号"
              initialValue={book.data.id}
              rules={[
                {
                  required: true,
                  message: '书籍号是必填项！',
                },
              ]}
            />
          )}

          <ProFormText
            width="lg"
            name="borrow_time"
            label="借阅时间"
            initialValue={newTime()}
            rules={[
              {
                required: true,
                message: '借阅时间是必填项！',
              },
            ]}
          />
          <ProFormText
            width="lg"
            name="num"
            label="数量"
            initialValue={1}
            rules={[
              {
                required: true,
                message: '数量是必填项！',
              },
            ]}
          />
          {currentUser.data && (
            <ProFormText
              width="lg"
              name="user_id"
              label="用户id"
              initialValue={currentUser.data.id}
              rules={[
                {
                  required: true,
                  message: '用户id是必填项！',
                },
              ]}
            />
          )}

        </div>

        {book.data && (
          <div
            style={{
              float: "left",
              overflow: "hidden",
              width: "200px",
              margin: "30px"
            }}
          >
            <Image
              src={book.data.picture}></Image>
          </div>
        )}

      </FormComponents>


    </>
  )
};
export default BorrowBox

